//
//  TJTabBar.swift
//  TJSinaWeibo
//
//  Created by 唐后能 on 16/4/8.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

class TJTabBar: UITabBar {

    // 定义外包属性.
    var composeClosure:(()->())?
    
    // MARK: 重新布局tabar的子控件frame.
    override func layoutSubviews() {
        super.layoutSubviews()
//        print("=====\(self.subviews)")
        var index = 0
        let btnWidth:CGFloat = self.frame.size.width / CGFloat(TJTabBarBtnCount)
        // 布局加好按钮的frame.
        composeBtn.frame = CGRectMake(2*btnWidth, 0, btnWidth, self.frame.size.height)
        // 重新布局其它四个子按钮.
        for item in self.subviews {
        
            if item.isKindOfClass(NSClassFromString("UITabBarButton")!) {
            
                item.frame = CGRectMake(CGFloat(index)*btnWidth, 0, btnWidth, self.frame.size.height)
                index += index == 1 ? 2 : 1
            }
        }
    }
    
    // MARK  - 加号按钮点击事件.
   @objc private func ComposeBtnClicked (){
    
        // 调用闭包:如果用! 闭包没实现会崩溃,用?保险些,相当于OC的判断block有实现.
        composeClosure?()
    }
    
    //MARK: - 懒加载加号按钮.
    lazy var composeBtn:UIButton = {
    
        let btn = UIButton()
        // 设置按钮属性.
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        self.addSubview(btn)
        
        // 给加号按钮添加点击事件.
        btn.addTarget(self, action: Selector("ComposeBtnClicked"), forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()

}
